import cv2
import numpy as np
import os
import plotly.graph_objects as go

def calculate_rgb_ratio(image_path):
    # 读取图片
    image = cv2.imread(image_path)
    # 将图片从 BGR 转换为 RGB 格式
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # 获取图片的宽度和高度
    height, width, _ = rgb_image.shape
    # 计算总像素数
    total_pixels = height * width
    # 初始化各颜色像素计数
    red_pixels = 0
    green_pixels = 0
    blue_pixels = 0
    # 遍历每个像素
    for i in range(height):
        for j in range(width):
            # 获取当前像素的 RGB 值
            r, g, b = rgb_image[i, j]
            # 判断像素颜色并计数
            if r > g and r > b:  # 红色像素
                red_pixels += 1
            elif g > r and g > b:  # 绿色像素
                green_pixels += 1
            elif b > r and b > g:  # 蓝色像素
                blue_pixels += 1
    # 计算各颜色占比
    red_ratio = red_pixels / total_pixels
    green_ratio = green_pixels / total_pixels
    blue_ratio = blue_pixels / total_pixels
    # 输出结果
    #print(f"Red ratio: {red_ratio:.4f}")
    #print(f"Green ratio: {green_ratio:.4f}")
    #print(f"Blue ratio: {blue_ratio:.4f}")
    return (int(red_ratio*100),int(green_ratio*100),int(blue_ratio*100),image_path)

# 示例调用
#print(calculate_rgb_ratio("pic/a0001.png"))
dict0={}
pic_folder='./pic/'
for file in os.listdir(pic_folder):
    dict0[file]=calculate_rgb_ratio(pic_folder+file)
    
#print(dict0)
points = []
for key in dict0:
    points.append(dict0[key])
print(points)
    #print(key,tuple(dict0[key]))
# 创建3D散点图
fig = go.Figure(data=[go.Scatter3d(
    x=[p[0] for p in points],
    y=[p[1] for p in points],
    z=[p[2] for p in points],
    mode='markers+text',
    marker=dict(
        size=8,
        #color=['red', 'green', 'blue', 'cyan', 'magenta'],
        opacity=0.8
    ),
    text=[f'{p[3]}' for p in points],  # 添加超链接
    textposition='top center'
)])

# 设置坐标轴标签
fig.update_layout(
    scene=dict(
        xaxis_title='X',
        yaxis_title='Y',
        zaxis_title='Z'
    ),
    title="3D Scatter Plot with Links"
)

# 显示图形
fig.show()
